<template>
  <div id="add_sos">
    <div class="top">
      <van-icon @click="toSecurityCenter()" name="arrow-left"/>
      <div class="title">添加紧急联系人</div>
    </div>
    <div class="content">
      <van-form @submit="onSubmit">
        <div class="title">姓名:</div>
        <van-field
            v-model="form.name"
            name="name"
            placeholder="请输入姓名"
            :rules="[{ required: true, message: '请输入姓名' }]"
        />
        <div class="title">手机号:</div>
        <van-field
            v-model="form.phone"
            name="phone"
            placeholder="请输入手机号"
            :rules="[{ required: true, message: '请输入手机号' }]"
        />
        <div class="bind">
          <van-button round block type="info" native-type="submit">添加</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>

import {addSos} from "@/api/purse/add_sos";

export default {
  data() {
    return {
      form: {
        name: '',
        userId: '',
        phone: '',
      },
    };
  },
  methods: {
    toSecurityCenter() {
      this.$router.go(-1);
    },
    onSubmit(values) {
      this.form.name = values.name;
      this.form.phone = values.phone;
      this.form.userId = localStorage.getItem("userId");
      const regex = /^1[3-9]\d{9}$/;
      if (regex.test(this.form.phone)) {
        addSos(this.form).then(res => {
          if (res.code === 1) {
            this.$toast.success('添加成功');
            this.$router.go(-1);
          } else {
            this.$toast.fail('添加失败');
          }
        });
      } else {
        this.$toast.fail('手机号格式错误');
      }
    },
  },
  created() {
  },
};
</script>

<style>
body {
  background-color: #F3FCFF;

  #add_sos {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;

    .top {
      width: 100%;
      height: 66px;
      background-color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      position: fixed;
      top: 0;

      .van-icon {
        font-size: 26px;
        position: absolute;
        left: 20px;
      }

      .title {
        font-size: 20px;
      }
    }

    .content {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin-top: 66px;

      .title {
        font-size: 20px;
        font-weight: bold;
        margin: 10px 0;
      }

      .van-field {
        width: 360px;
        height: 60px;
        margin: 0 0 10px 0;
        border-radius: 10px;
        border: 1px solid #CDCECE;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .bind {
        width: 360px;
        height: 60px;
        margin: 30px 0;

        .van-button {
          width: 100%;
          height: 70%;
          font-size: 16px;
          background-color: #4EA9CB;
        }
      }
    }
  }
}
</style>